package com.org.litepal.slice.crud;

import com.org.litepal.ResourceTable;
import com.org.litepal.model.Singer;
import com.org.litepal.provider.DataItemProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.resultset.ResultSet;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

public class SaveSampleAbilitySlice extends AbilitySlice {
    private TextField mSingerNameEdit;

    private TextField mSingerAgeEdit;

    private TextField mSingerGenderEdit;

    private RoundProgressBar mProgressBar;

    private DataItemProvider mAdapter;

    private ArrayList<List<String>> mList = new ArrayList<>();
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_save_sample);
        mProgressBar = (RoundProgressBar) findComponentById(ResourceTable.Id_progressSave_bar);
        mSingerNameEdit =(TextField) findComponentById(ResourceTable.Id_save_name_edit);
        mSingerAgeEdit =(TextField)  findComponentById(ResourceTable.Id_save_age_edit);
        mSingerGenderEdit =(TextField)  findComponentById(ResourceTable.Id_save_gender_edit);
        Button mSaveBtn = (Button) findComponentById(ResourceTable.Id_save_btn);
        ListContainer mDataListView = (ListContainer) findComponentById(ResourceTable.Id_dataSave_list_view);
        mSaveBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    Singer singer = new Singer();
                    singer.setName(mSingerNameEdit.getText().toString());
                    singer.setAge(Integer.parseInt(mSingerAgeEdit.getText().toString()));
                    singer.setMale(Boolean.parseBoolean(mSingerGenderEdit.getText().toString()));
                    singer.save();
                    refreshListView(singer.getId(), singer.getName(), singer.getAge(),
                            singer.isMale() ? 1 : 0);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastDialog dialog = new ToastDialog(getContext());
                    dialog.setText("Param is not valid.");
                    dialog.setDuration(1500);
                    dialog.show();
                }
            }
        });
        mAdapter = new DataItemProvider(mList,this.getContext());
        mDataListView.setItemProvider(mAdapter);
        populateDataFromDB();
    }

    private void populateDataFromDB() {
        mProgressBar.setVisibility(Component.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                mList.clear();
                List<String> columnList = new ArrayList<String>();
                columnList.add("id");
                columnList.add("name");
                columnList.add("age");
                columnList.add("ismale");
                mList.add(columnList);
                ResultSet cursor = null;
                try {
                    cursor = Connector.getDatabase().querySql("select * from singer order by id",
                            null);
                    if (cursor.goToFirstRow()) {
                        do {
                            long id = cursor.getLong(cursor.getColumnIndexForName("id"));
                            String name = cursor.getString(cursor.getColumnIndexForName("name"));
                            int age = cursor.getInt(cursor.getColumnIndexForName("age"));
                            int isMale = cursor.getInt(cursor.getColumnIndexForName("ismale"));
                            List<String> stringList = new ArrayList<String>();
                            stringList.add(String.valueOf(id));
                            stringList.add(name);
                            stringList.add(String.valueOf(age));
                            stringList.add(String.valueOf(isMale));
                            mList.add(stringList);
                        } while (cursor.goToNextRow());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                    handler.postTask(() -> {
                            mProgressBar.setVisibility(Component.HIDE);
                            mAdapter.notifyDataChanged();
                        });
                }
            }
        }).start();
    }
    private EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
    @Override
    protected void onStop() {
        super.onStop();
        handler.removeAllEvent();
    }
    private void refreshListView(long id, String name, int age, int isMale) {
        List<String> stringList = new ArrayList<String>();
        stringList.add(String.valueOf(id));
        stringList.add(name);
        stringList.add(String.valueOf(age));
        stringList.add(String.valueOf(isMale));
        mList.add(stringList);
        mAdapter.notifyDataChanged();
//        mDataListView.setSelectedItemIndex(mList.size());
    }
}
